import React from 'react';
import { InputNumber } from 'antd';
import { InputFromIntervalProps, InputFromIntervalState } from '../data';

const currentYear = new Date().getUTCFullYear();

/**
 * cron时间表达式生成器-年面板
 * 属性如下：
 */
class InputFromInterval extends React.PureComponent<InputFromIntervalProps, InputFromIntervalState> {

  state: InputFromIntervalState = {
    from: currentYear,
    interval: 1
  }

  /**
   * 静态函数，根据新传入的props来映射到state。
   * 该函数必须有返回值。当props传入的内容不需要影响state，就必须返回一个null
   */
  static getDerivedStateFromProps(nextProps: InputFromIntervalProps, prevState: InputFromIntervalState) {
    // console.log('InputFromTo.getDerivedStateFromProps: ', nextProps, prevState);
    // 重新查询清空表格勾选
    const { disabled, value } = nextProps;
    if (disabled) {
      return {
        from: currentYear,
        interval: 1
      };
    } else {
      if (value) {
        const [from, interval] = value.split('/').map((v) => parseInt(v, 10));
        return {
          from,
          interval
        }
      }
    }
    return null;
  }

  onChangeFrom = (value: number | null) => {
    const { onChange } = this.props;
    const { interval } = this.state;
    if (value) {
      this.setState({
        from: value
      });
      if (onChange) {
        onChange(`${value || currentYear}/${interval}`);
      }
    }
  }

  onChangeInterval = (value: number | null) => {
    const { onChange } = this.props;
    const { from } = this.state;
    if (value) {
      this.setState({
        interval: value
      });
      if (onChange) {
        onChange(`${from}/${value || 1}`);
      }
    }
  }

  render() {
    const { disabled } = this.props;
    let { from, interval } = this.state;

    return (
      <React.Fragment>
        周期从&nbsp;
        <InputNumber
            disabled={disabled}
            min={currentYear}
            max={9999}
            value={from}
            onChange={this.onChangeFrom}
            style={{ width: 100 }}
        />
        &nbsp;年开始，每&nbsp;
        <InputNumber
            disabled={disabled}
            min={1}
            max={99}
            value={interval}
            onChange={this.onChangeInterval}
            style={{ width: 100 }}
        />
        &nbsp;年执行一次
      </React.Fragment>
    );
  }

}

export default InputFromInterval;